import MXR from '../common/encryption'

export default {
  /**
   * 格式指定时间格式
   *
   * @param value 指定时间
   * @returns {string}
   */
  formate: function (value) {
    let date = new Date(value);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s;
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
  },

  /**
   * 格式指定时间格式
   *
   * @param date 指定时间
   * @returns {string}
   */
  formatTime: function (date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  },

  /**
   * 计算连两个时间之间的秒数差
   * @param start 开始时间
   * @param end 结束时间
   * @returns {number}
   */
  secondTimeBetween: function (start, end) {
    let date = start.getTime() - end.getTime()
    return Math.floor(date / 1000)
  },

  /**
   * 根据秒数转成时分秒
   * @param s 秒数
   * @returns {string}
   */
  secToTime: function (s) {
    s = Math.abs(s)

    let hour = Math.floor(s / 3600)
    let min = Math.floor(s / 60) % 60
    let sec = s % 60

    return [hour, min, sec].map(formatNumber).join(':')
  },

  /**
   * 根据指定时间返回与当前时间的中文时间差
   * @param time 指定时间戳
   * @returns {string}
   */
  judgeTimeToString: function (time) {
    let dateNow = new Date()
    let timestamp = dateNow.valueOf()
    let second = ((timestamp - time) / 1000)
    let diffMinute = Math.ceil(second / 60)

    if (diffMinute < 60) {
      return diffMinute + '分钟前'
    } else {
      let minute = second / 60
      let diffHour = Math.ceil(minute / 60)

      if (diffHour < 24) {
        return diffHour + '小时前'
      } else {
        let hour = minute / 60
        let diffDay = Math.ceil(hour / 24)

        if (diffDay === 1) {
          return '昨天'
        } else if (diffDay < 7) {
          return diffDay + '天前'
        } else {
          let year = dateNow.getFullYear()
          let requestDate = new Date(time)
          let requestYear = requestDate.getFullYear()
          let requestMonth = requestDate.getMonth() + 1
          let requestDay = requestDate.getDate()

          let returnMonth = requestMonth < 10 ? '0' + requestMonth : requestMonth
          let returnDay = requestDay < 10 ? '0' + requestDay : requestDay
          if (year === requestYear) {
            return returnMonth + '-' + returnDay
          } else {
            return requestYear + '-' + returnMonth + '-' + returnDay
          }
        }
      }
    }
  },

  /**
   * 获取URL中的参数
   * @param name 参数名
   * @returns {*}
   */
  getQueryString: function (name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    let r = window.location.search.substr(1).match(reg)
    if (r !== null) return r[2]
    return null
  },

  /**
   * 创建cookie
   * @param name cookie名
   * @param value cookie值
   */
  createCookie: function (name, value) {
    let d = new Date()
    d.setTime(d.getTime() + (20 * 24 * 60 * 60 * 1000))
    let expires = 'expires=' + d.toGMTString()
    document.cookie = name + '=' + value + '; ' + expires
  },

  /**
   * 获取cookie内容
   * @param cname cookie名
   */
  getCookie: function (cname) {
    getCookie(cname)
  },

  /**
   * 删除指定cookie
   * @param cname cookie
   */
  deleteCookie: function (cname) {
    let exp = new Date()
    exp.setTime(exp.getTime() - 1)
    let cval = getCookie(cname)
    if (cval != null) {
      document.cookie = cname + '=' + cval + ';expires=' + exp.toGMTString()
    }
  },

  /**
   * 创建请求header
   * @param to 路由守卫
   * @param appVersion 版本号
   */
  createMxrHeader: function (to, appVersion) {
    let header = {
      userId: to.query.uid || 0,
      deviceId: to.query.deviceId || '',
      deviceUnique: to.query.deviceUnique || '',
      appVersion: to.query.v || '0.0.0',
      osType: 4
    }

    return localStorage.setItem('mxr-key', MXR.encryptionMxr(JSON.stringify(header), true))
  },

  /**
   * 检测版本号
   * @param ver 版本号
   * @returns 整数数据
   */
  checkVersion: function (ver) {
    try {
      let verNums = ver.split('.')
      return toInt32NoException(verNums[0]) * 1000000 + toInt32NoException(verNums[1]) * 1000 + toInt32NoException(verNums[2])
    } catch (e) {
      return 0
    }
  },

  /**
   * HTML内容转变为TEXT
   * @param html HTML内容
   * @returns 转换后的结果
   */
  htmlToText: function (html) {
    html = html.replace(/(\n)/g, '')
    html = html.replace(/(\t)/g, '')
    html = html.replace(/(\r)/g, '')
    html = html.replace(/<\/?[^>]*>/g, '')
    html = html.replace(/\s*/g, '')
    html = html.substring(0, 60)
    return html
  },

  /**
   * 递归获取指定DOM元素的每个子元素
   * @param dom DOM对象
   * @param nodes 节点
   */
  traversal: function (dom, nodes) {
    let len = dom.length
    let d = null
    for (let i = 0; i < len; i++) {
      d = dom[i]
      nodes.push(d)
      if (d.children) {
        traversal(d.children, nodes)
      }
    }
  },

  /**
   * 递归获取指定DOM元素中图片的节点
   * @param nodes 节点
   */
  getImage: function (nodes) {
    for (let nodesKey in nodes) {
      if (nodes[nodesKey].nodeName.toLowerCase() === 'img') {
        return nodes[nodesKey]
      }
    }
  },

  /**
   * 获取浏览器可视区域高度
   * @returns {number}
   */
  clientHeight: function () {
    return document.documentElement.clientHeight
  },

  /**
   * 获取浏览器可视区域宽度
   * @returns {number}
   */
  clientWidth: function () {
    return document.documentElement.clientWidth
  },

  /**
   * 初始化资源ICON
   *
   * @param type 资源类型
   */
  returnResSupTypeIcon: function (type) {
    switch (parseInt(type)) {
      case -10:
      case 0:
      case 1:
      case 2:
      case 6:
        return require('../assets/images/btn_select_3D_OFF.png')
      case 3:
        return require('../assets/images/btn_Video_OFF.png')
      case 4:
        return require('../assets/images/btn_Image_OFF.png')
      case 5:
        return require('../assets/images/btn_Parano_OFF.png')
      case 7:
        return require('../assets/images/icon_animation@1x.png')
      case 8:
        return require('../assets/images/icon_2Dgame@1x.png')
      case 9:
        return require('../assets/images/icon_audio@1x.png')
      case 10:
        return require('../assets/images/icon_ppt@1x.png')
      default:
        return require('../assets/images/btn_cus3D.png')
    }
  },

  /**
   * 返回资源列表的资源ICON
   * @param type 资源类型
   */
  returnResListTypeIcon: function (type) {
    switch (parseInt(type)) {
      case -10:
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 9:
      case 10:
        return require('../assets/images/btn_select_3D_OFF.png')
      case 6:
        return require('../assets/images/btn_Video_OFF.png')
      case 7:
        return require('../assets/images/btn_Image_OFF.png')
      case 8:
        return require('../assets/images/btn_Parano_OFF.png')
      case 11:
        return require('../assets/images/icon_animation@1x.png')
      case 12:
      case 15:
        return require('../assets/images/icon_2Dgame@1x.png')
      case 13:
        return require('../assets/images/icon_audio@1x.png')
      case 14:
        return require('../assets/images/icon_ppt@1x.png')
      default:
        return require('../assets/images/btn_cus3D.png')
    }
  },

  /**
   * 是否为3D模型,以详情页的subType判断
   *
   * @param type 资源类型
   * @returns {boolean} true=是，false=否
   */
  is3DModel: function (type) {
    switch (parseInt(type)) {
      case -10:
      case 0:
      case 1:
      case 2:
      case 6:
        return true
      default:
        return false
    }
  },

  /**
   * 是否为模型，以资源列表里的type判断
   *
   * @param type 资源类型
   * @returns {boolean} true=是，false=否
   */
  isModel: function (type) {
    switch (parseInt(type)) {
      case -10:
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 9:
      case 10:
        return true
      default:
        return false
    }
  }
}



function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getCookie(cname) {
  let name = cname + '='
  let ca = document.cookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i].trim()
    if (c.indexOf(name) === 0) return c.substring(name.length, c.length)
  }

  return ''
}

function toInt32NoException(str) {
  if (isNaN(str)) {
    return 0
  } else {
    return parseInt(str)
  }
}
